package com.wildwolf.project.wildwolf.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public final class HttpAPI {
	private static final String TAG = HttpAPI.class.getSimpleName();
	private static final String CHARSET = HTTP.UTF_8;
	private static HttpClient encounterHttpClient;

	public static synchronized HttpClient getHttpClient() {
		if (encounterHttpClient == null) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			// HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "+
			// "AppleWebKit/51(KHTML,like Gecko) Version/4.0 Mobile Safari/51");
			// 超时设置
			/* 从连接池中取连接的超时时间 ConnectionPoolTimeoutException,与 */
			/**
			 * 第一行设置ConnectionPoolTimeout：这定义了从ConnectionManager管理的连接池中取出连接的超时时间
			 * ，此处设置为1秒。
			 */
			ConnManagerParams.setTimeout(params, 1000);
			/* 连接超时 ConnectionTimeoutException */
			/**
			 * 第二行设置ConnectionTimeout：这定义了通过网络与服务器建立连接的超时时间。
			 * Httpclient包中通过一个异步线程去创建与服务器的socket连接，这就是该socket连接的超时时间，此处设置为2秒。
			 */
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			/* 请求超时 SocketTimeoutException */
			/**
			 * 　第三行设置SocketTimeout：这定义了Socket读数据的超时时间，即从服务器获取响应数据需要等待的时间，此处设置为4秒
			 * 。
			 */
			HttpConnectionParams.setSoTimeout(params, 4000);
			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schemeRegistry.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));
			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(
					params, schemeRegistry);
			encounterHttpClient = new DefaultHttpClient(
					clientConnectionManager, params);
		}
		return encounterHttpClient;
	}

	public static boolean abort(){
		encounterHttpClient.getConnectionManager().shutdown();
		return true;
	}
	/**
	 * 
	 * @param url
	 * @return
	 */
	public static String post(String url, List<NameValuePair> nameValuePair) throws Exception {
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePair, CHARSET);
			// 创建POST请求
			HttpPost request = new HttpPost(url);
			request.setEntity(entity);
			// 发送请求
			HttpClient client = HttpAPI.getHttpClient();
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity resEntity = response.getEntity();
			return (resEntity == null) ? null : EntityUtils.toString(resEntity,
					CHARSET);
		} catch (UnsupportedEncodingException e) {
			Log.w(TAG, e.getMessage());
			return null;
		} catch (SocketTimeoutException ste) {
			Log.w(TAG, ste.getMessage());
			throw new RuntimeException("请求超时", ste);
		} catch (ConnectionPoolTimeoutException spe) {
			Log.w(TAG, spe.getMessage());
			throw new RuntimeException("在连接池取连接超时", spe);
		} catch (ConnectTimeoutException cte) {
			Log.w(TAG, cte.getMessage());
			throw new RuntimeException("连接超时", cte);
		} catch (ClientProtocolException cpe) {
			Log.w(TAG, cpe.getMessage());
			throw new RuntimeException("客户端网络协议错误", cpe);
		} catch (IOException e) {
			throw new RuntimeException("网络连接失败", e);
		}
	}
}
